<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:brand:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:brand:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:brand:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:brand:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="brandList"
      :default-sort="tableSort"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="品牌名称" align="center" prop="brandName" />
      <el-table-column label="排序" align="center" prop="sortNum" />
      <el-table-column label="logo" align="center" prop="logo" >
        <template #default="scope">
          <el-image v-if="scope.row.logo" :src="scope.row.logo"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
        sortable="custom"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:brand:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:brand:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page="queryParams.pageNum"
      :limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="品牌名称" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input v-model="form.sortNum" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="logo" prop="logo">
          <el-upload
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess"
            accept="image/png, image/jpeg"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogCancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Brand">
import { ref, toRefs } from "vue";
import {
  listBrand,
  getBrand,
  delBrand,
  addBrand,
  updateBrand,
  exportXlsUrl,
} from "@/api/product/brand";
import { uploadUrl, uploadHeaders } from "@/api/system/common";
import logo from '@/assets/logo/logo.png';

const { proxy } = getCurrentInstance();

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 品牌表格数据
const brandList = ref([]);
// 弹出层标题
const dialogTitle = ref("");
// 是否显示弹出层
const dialogVisible = ref(false);

const fileList = ref<[]>([])
const imageUrl = ref('')
const previewDialogVisible = ref(false)


const handleRemove = (file, files) => {
  console.log(file, fileList)
   fileList.value = files.filter(item=>{
    return item.url!==file.url;
  })
}
const handlePictureCardPreview = (file) => {
  imageUrl.value = file.url
  previewDialogVisible.value = true
}

const handleUploadSuccess = (res, file) =>{
  imageUrl.value = res.data;
  form.value.logo = res.data;
}

// 查询参数
const reactiveData = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    brandName: null,
    params: {
      sort: "createTime",
      order: "descending",
    },
  },
  form: {},
  rules: {
    brandName: [
      { required: true, message: "品牌名称不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(reactiveData);

const tableSort = computed(() => {
  if (queryParams.value.params.sort) {
    return {
      prop: queryParams.value.params.sort,
      order: queryParams.value.params.order,
    };
  }
  return null;
});

/** 查询品牌列表 */
function getList() {
  loading.value = true;
  listBrand(queryParams.value).then((response) => {
    brandList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 取消按钮
function handleDialogCancel() {
  dialogVisible.value = false;
  reset();
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    brandName: null,
    sortNum: null,
    logo: null,
    remark: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
  };
  proxy.resetForm("formRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryFormRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

// 排序
function handleSortChange({ column, prop, order }) {
  queryParams.value.params.sort = prop ? prop : null;
  queryParams.value.params.order = order ? order : null;
  getList();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  dialogVisible.value = true;
  dialogTitle.value = "添加品牌";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getBrand(id).then((response) => {
    form.value = response.data;
    dialogVisible.value = true;
    dialogTitle.value = "修改品牌";
  });
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateBrand(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          dialogVisible.value = false;
          getList();
          reset();
        });
      } else {
        addBrand(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          dialogVisible.value = false;
          getList();
          reset();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  const opIds = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除品牌编号为"' + opIds + '"的数据项？')
    .then(function () {
      return delBrand(opIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    exportXlsUrl,
    {
      ...queryParams.value,
    },
    `brand_${new Date().getTime()}.xlsx`
  );
}
/** 初始化数据 **/
getList();
</script>
